package com.gxks.lhs.filter;

import com.gxks.lhs.security.JwtTokenProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class JwtTokenFilter extends OncePerRequestFilter {

    private JwtTokenProvider jwtTokenProvider;

    public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }

    private List<String> excludedPaths = Arrays.asList("/login", "/refresh", "/health-check", "/doc.html");


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 如果请求路径在排除列表内，则跳过Token验证
//        if (!excludedPaths.contains(request.getRequestURI())) {
        // 从请求中提取token
        String token = request.getHeader("Authorization");

        logger.info("JWT Token: " + token);
        logger.info(request.getRequestURI());
        if (token != null) {
            //获取token
//                token = token.replace("Bearer ", "");
            logger.info("JWT Token: " + token);
            // 验证token是否有效
            if (jwtTokenProvider.validateAccessToken(token)) {
                // 获取经过验证的Authentication对象
                Authentication authentication = jwtTokenProvider.getAuthenticationFromAccessToken(token);
                if (authentication != null) {
                    // 将Authentication对象设置为当前线程的上下文中的Authentication对象
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }


//        }

        // 继续执行过滤器链中的下一个过滤器
        filterChain.doFilter(request, response);
    }

}
